package com.gy.bearhelps.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.gy.bearhelps.MyApplication;
import com.gy.bearhelps.R;
import com.gy.bearhelps.base.BaseActivity;
import com.gy.bearhelps.navi.SingleRouteCalculateActivity;
import com.gy.bearhelps.util.AnimUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：gy on 16/11/6
 * 说明：妇幼保健院
 */
public class MapSearchActivity extends BaseActivity implements PoiSearch.OnPoiSearchListener,AMap.InfoWindowAdapter,
        AMap.OnMapClickListener,AMap.OnMarkerClickListener,AMap.OnInfoWindowClickListener{


    public final static int POI_DISTANCE = 100 * 1000;// 附近点距离
    private ImageView imgBack;
    private MapView mapView;
    private AMap aMap;
    private LatLng center;//地图中心点
    private List<Marker> showMarkers;//当前地图上显示的marker
    private PoiSearch poiSearch;// 周边搜索
    private PoiSearch.Query query;// 周边搜索条件
    private PoiResult poiResult;// 搜索结果
    private double x, y;//传参中心点坐标
    private Marker clickMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_search);
        imgBack = (ImageView) findViewById(R.id._back);
        mapView = (MapView) findViewById(R.id.activity_map);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        initDatas();
        setListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    public void initDatas(){
        showMarkers = new ArrayList<>();
    }

    public void setListeners() {
        showToast("正在进行搜索，请稍后！！！");
        imgBack.setOnClickListener(this);
        center = new LatLng(MyApplication.aMapLocation.getLatitude(),MyApplication.aMapLocation.getLongitude());
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);//设置地图缩放按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置地图zoom级别
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(center));
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.addMarker(new MarkerOptions()
                .position(center)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.mipmap.activity_map_near_marker))
                .draggable(true));
        startSearch();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id._back:
                finish();
                AnimUtil.pushRightInAndOut(this);
                break;
        }
    }

    /** 设置周边搜索条件*/
    private void startSearch() {
        query = new PoiSearch.Query("妇幼保健院", "", MyApplication.aMapLocation.getCityCode());
        //        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页
        query.setPageSize(50);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(center.latitude,
                center.longitude), POI_DISTANCE, true));//设置收缩条件
        poiSearch.searchPOIAsyn();//开始搜索
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            // 搜索POI的结果
            if (result != null && result.getQuery() != null) {
                // 是否是同一条
                if (result.getQuery().equals(query)) {
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    int resultPages = poiResult.getPageCount();
                    // 取得第一页的poiitem数据，页数从数字0开始
                    List<PoiItem> poiItems = poiResult.getPois();
                    // 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    List suggestionCities = poiResult
                            .getSearchSuggestionCitys();

                    if (poiItems != null && poiItems.size() > 0) {
                        showSearchResult(poiItems);
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        // 没有搜索到数据
                        showToast("很遗憾，附近没有搜索结果！");
                    } else {
                        // 没有搜索到数据
                        showToast("很遗憾，附近没有搜索结果！");
                    }
                }
            } else {
                showToast("很遗憾，附近没有搜索结果！");
            }
        } else {
            showToast("对不起，请稍后重试!");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /** 显示搜索结果 */
    private void showSearchResult(List<PoiItem> list) {
        double minLat = 0,minLong = 0,maxLat = 0,maxLong = 0;
        if(list.size() > 1){
            minLat = Double.valueOf(list.get(0).getLatLonPoint().getLatitude());
            maxLat = Double.valueOf(list.get(0).getLatLonPoint().getLatitude());
            minLong = Double.valueOf(list.get(0).getLatLonPoint().getLongitude());
            maxLong = Double.valueOf(list.get(0).getLatLonPoint().getLongitude());
        }else if(list.size() == 1){
            minLat = Double.valueOf(y);
            maxLat = Double.valueOf(y);
            minLong = Double.valueOf(x);
            maxLong = Double.valueOf(x);
        }
        for (PoiItem item : list) {
            LatLng loc = new LatLng(item.getLatLonPoint().getLatitude(), item
                    .getLatLonPoint().getLongitude());
            Marker marker = aMap.addMarker(new MarkerOptions().position(loc)
                    .icon( BitmapDescriptorFactory
                            .fromResource(R.mipmap.ic_search_marker)).draggable(true)
                    .title(item.getTitle()).snippet(item.getSnippet()));
            showMarkers.add(marker);

            if(Double.valueOf(item.getLatLonPoint().getLatitude()) < minLat ){
                minLat = Double.valueOf(item.getLatLonPoint().getLatitude());
            }
            if(Double.valueOf(item.getLatLonPoint().getLatitude()) > maxLat ){
                maxLat = Double.valueOf(item.getLatLonPoint().getLatitude());
            }
            if(Double.valueOf(item.getLatLonPoint().getLongitude()) < minLong ){
                minLong = Double.valueOf(item.getLatLonPoint().getLongitude());
            }
            if(Double.valueOf(item.getLatLonPoint().getLongitude()) > maxLong ){
                maxLong = Double.valueOf(item.getLatLonPoint().getLongitude());
            }
        }

        LatLng west = new LatLng(minLat,minLong);
        LatLng east = new LatLng(maxLat,maxLong);
        LatLngBounds bounds = new LatLngBounds(west,east);
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
        aMap.invalidate();
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View windowView = View.inflate(this,R.layout.view_amap_detail_marker,null);
        TextView tvTitle = (TextView) windowView.findViewById(R.id.view_amap_detail_tv_title);
        TextView tvAddress = (TextView) windowView.findViewById(R.id.view_amap_detail_tv_address);
        tvTitle.setText(marker.getTitle());
        tvAddress.setText(marker.getSnippet());
        return windowView;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        clickMarker.hideInfoWindow();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        clickMarker = marker;
        return false;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        Intent intent = new Intent(this, SingleRouteCalculateActivity.class);
        intent.putExtra("endLat",marker.getPosition().latitude);
        intent.putExtra("endLong",marker.getPosition().longitude);
        startActivity(intent);
    }
}
